import pinyin from "./pinyin";
import zhuyin from './zhuyin'

export interface LookforStringResultWord {
    word: string;
    yin: string[]
    yinIndex: number,
    useSelect: boolean,
}

export const handler = {
    _data: [{}, {}],

    init() {
        this.load(0, pinyin);
        this.load(1, zhuyin);
    },

    load(type: number, oriData: string) {
        let begin = 0;
        const data: any = this._data[type];
        while (begin < oriData.length) {
            const wordPos = oriData.indexOf(' ', begin);
            if (wordPos == -1) break;
            let lineEndPos = oriData.indexOf('\n', wordPos + 1);
            if (lineEndPos == -1) lineEndPos = oriData.length;

            const yin = oriData.substring(wordPos + 1, lineEndPos);
            data[oriData.substring(begin, wordPos)] = yin.split(',')

            begin = lineEndPos + 1;
        }
    },

    /**
     * 
     * @param {*} word 
     * @param {*} type 0-pinyin, 1-zhuyin
     */
    lookfor(word: string, type: number): string[] {
        const data: any = this._data[type];
        return data[word];
    },

    lookforString(str: string, type: number) : LookforStringResultWord[] {
        const chars: string[] = [];
        for(let i = 0; i < str.length; ++i) {
            const charCode = str.charCodeAt(i);
            // 扩展区汉字
            if (charCode >= 0xd800 && charCode <= 0xdfff) {
                chars.push(str.substring(i, i + 2))
                ++i;
            } else {
                chars.push(str.substring(i, i + 1))
            }
        }

        const ret:LookforStringResultWord[] = [];
        chars.forEach((c)=>{
            const item: LookforStringResultWord = {
                word: c,
                yin: this.lookfor(c, type),
                yinIndex: 0,
                useSelect: false
            }
            ret.push(item)
        })

        return ret;
    }
}